package com.finupgroup.postloan.generator.config;

import com.finupgroup.postloan.generator.PropUtils;
import com.finupgroup.postloan.generator.config.converts.MySqlTypeConvert;
import com.finupgroup.postloan.generator.config.querys.MySqlQuery;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 数据库配置
 *
 * @author YueQingwei
 * @since 2018-04-10
 */
public class DataSourceConfig {

    /**
     * 数据库信息查询
     */
    private IDbQuery dbQuery;
    /**
     * 类型转换
     */
    private ITypeConvert typeConvert;
    /**
     * 驱动连接的URL
     */
    private String url;
    /**
     * 驱动名称
     */
    private String driverName = "com.mysql.jdbc.Driver";
    /**
     * 数据库连接用户名
     */
    private String username;
    /**
     * 数据库连接密码
     */
    private String password;

    public DataSourceConfig() {
        this.url = PropUtils.get("db.url");
        this.username = PropUtils.get("db.username");
        this.password = PropUtils.get("db.password");
        dbQuery = new MySqlQuery();
        typeConvert = new MySqlTypeConvert();
    }

    public IDbQuery getDbQuery() {
        return dbQuery;
    }

    public ITypeConvert getTypeConvert() {
        return typeConvert;
    }

    /**
     * 创建数据库连接对象
     *
     * @return Connection
     */
    public Connection getConn() {
        Connection conn;
        try {
            Class.forName(driverName);
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException("获取数据库连接失败", e);
        }
        return conn;
    }
}
